/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.web.util;

import org.vacoor.nothing.common.util.Castor;
import org.vacoor.nothing.common.util.ThreadContext;
import org.vacoor.nothing.web.entity.Variable;
import org.vacoor.nothing.web.service.ConfigurationManager;

import java.util.Properties;

import static org.vacoor.nothing.common.util.Nulls.nvl;

/**
 * @author vacoor
 */
public abstract class SettingsUtils {
    public static final String THREAD_CONFIG_MANAGER_KEY = SettingsUtils.class.getName() + ".THREAD_CONFIG_MANAGER_KEY";
    private static ConfigurationManager configurationManager;

    public static Boolean getBoolean(String var, Boolean def) {
        return nvl(getBoolean(var), def);
    }

    public static Integer getInt(String var, Integer def) {
        return nvl(getInt(var), def);
    }

    public static String get(String var, String def) {
        return nvl(get(var), def);
    }

    public static Boolean getBoolean(String var) {
        return Castor.asBoolean(get(var));
    }

    public static Integer getInt(String var) {
        return Castor.asInt(get(var));
    }

    public static String get(String var) {
        Variable variable = getConfigurationManager().find(var);
        return null != variable ? variable.getValue() : null;
    }

    public static Properties getProperties() {
        return getConfigurationManager().getConfiguration();
    }

    public static void setConfigurationManager(ConfigurationManager configurationManager) {
        SettingsUtils.configurationManager = configurationManager;
    }

    public static ConfigurationManager getConfigurationManager() {
        ConfigurationManager configMgr = (ConfigurationManager) ThreadContext.get(THREAD_CONFIG_MANAGER_KEY);
        if (null == configMgr) {
            configMgr = configurationManager;
        }
        if (configMgr == null) {
            String msg = "No ConfigurationManager accessible to the calling code, either bound to the " + SettingsUtils.class.getName() + " or as a vm static singleton.  This is an invalid application configuration.";
            throw new IllegalStateException(msg);
        }
        return configMgr;
    }

    private SettingsUtils() {
    }
}
